//package com.hxs.hxsserver.socketServer;
//
//import com.hxs.hxsserver.domain.entity.device.Device;
//import com.hxs.hxsserver.service.SSEService;
//import com.hxs.hxsserver.utils.ByteUtil;
//import com.hxs.hxsserver.utils.CRCUtil;
//import lombok.extern.slf4j.Slf4j;
//
//import java.io.*;
//import java.net.Socket;
//import java.net.SocketTimeoutException;
//import java.util.Map;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//import java.util.concurrent.ScheduledExecutorService;
//import java.util.concurrent.TimeUnit;
//
///**
// * 客户端处理类
// * @author liuchuan
// * @create 2024/9/25
// */
//@Slf4j
//public  class ClientHandler implements Runnable {
//    private final Socket clientSocket;
//    private SSEService sseService;
//    private Map<String, ClientHandler> clientHandlers;
//    private final ExecutorService executorService = Executors.newCachedThreadPool();
//    private ScheduledExecutorService heartbeatScheduler;
//
//    public ClientHandler(Socket socket, SSEService sseService,Map<String, ClientHandler> clientHandlers) {
//        this.clientSocket = socket;
//        this.sseService = sseService;
//        this.clientHandlers = clientHandlers;
//        startHeartbeat();
//    }
//
//    @Override
//    public void run() {
//        String deviceHardwareAddr="";
//        try (InputStream inputStream = clientSocket.getInputStream();
//             OutputStream outputStream = clientSocket.getOutputStream()) {
//
//            byte[] buffer = new byte[1024];
//            int bytesRead;
//
//            while ((bytesRead = inputStream.read(buffer)) != -1) {
//
//                // 将接收到的字节转换为十六进制字符串并打印（可选）
//                String messageHex = ByteUtil.bytesToHex(buffer, bytesRead);
//                log.info("收到消息来至客户端 (Hex)"+ clientSocket.getInetAddress().getHostAddress()+": "+ messageHex);
//                // 将消息通过 device 发送到前端
////                sseService.sendMessage(messageHex,messageHex.substring(4, 14));
//                 deviceHardwareAddr = messageHex.substring(4, 14);
//                ClientHandler handler = clientHandlers.get(deviceHardwareAddr);
//                if(handler==null){
//                    // 存储客户端
//                    ClientHandler clientHandler = new ClientHandler(clientSocket, sseService,clientHandlers);
//                    clientHandlers.put(deviceHardwareAddr, clientHandler);
//                }
//                //todo 罗辑还需要修改
//                try {
//                    executorService.submit(() -> {
//                        //写数据库
//                        sseService.saveOrUpdate(new Device(clientSocket.getInetAddress().getHostAddress()),messageHex);
//                    });
//                } catch (Exception e) {
//                    log.info("写入数据库错误");
//                    e.printStackTrace();
//                }
//
//                // 直接将接收到的字节在第十四位加上时间戳字符串，再根据整体这个字符串计算出crc四位校验码
//                // 获取当前时间的毫秒时间戳
//                long currentTimeMillis = System.currentTimeMillis();
//                // 转换为十六进制字符串
//                String timestampHex = String.format("%016x", currentTimeMillis);
//                System.out.println("时间戳的十六进制为："+ timestampHex );
//                String massage = messageHex.substring(0, 14) + timestampHex ;
//                // 计算 CRC
//                String s = CRCUtil.calculateCRC16(massage.getBytes());// 将 CRC 转换为字节数组
//                System.out.println("CRC校验码为："+ s );
//                byte[] bytes = ByteUtil.hexStringToByteArray(massage + s);
//
//                outputStream.write(bytes, 0, bytes.length); // 发送接收到的字节
//                outputStream.flush(); // 确保数据被发送
//                String messageHex2 = ByteUtil.bytesToHex(bytes, bytes.length);
//                log.info("发送消息 (Hex): " + messageHex2);
//            }
//
//            log.info("客户端已断开连接: " + clientSocket.getInetAddress());
//            //关闭改变设备状态
//            sseService.updateStatusDevice(deviceHardwareAddr,0);
//        } catch (IOException e) {
//            log.error("读取消息时出错: " + e.getMessage());
//        } finally {
//            try {
//                clientSocket.close(); // 关闭客户端连接
//                // 从 clientHandlers 中移除
//                clientHandlers.remove(deviceHardwareAddr);
//            } catch (IOException e) {
//                log.error("关闭连接时出错: " + e.getMessage());
//            }
//        }
//    }
//
//
//    public void sendMessage(String message) {
//        try {
//            OutputStream outputStream = clientSocket.getOutputStream();
//            // 将十六进制字符串转换为字节数组
//            byte[] bytes = ByteUtil.hexStringToByteArray(message);
//            outputStream.write(bytes);
//            outputStream.flush();
//            log.info("主动发送消息: " + message);
//        } catch (IOException e) {
//            log.error("发送消息时出错: " + e.getMessage());
//        }
//    }
//
//    private void startHeartbeat() {
//        heartbeatScheduler = Executors.newSingleThreadScheduledExecutor();
//        heartbeatScheduler.scheduleAtFixedRate(() -> {
//            sendHeartbeat();
//        }, 0, 60, TimeUnit.SECONDS); // 每30秒发送一次心跳
//    }
//
//    private void sendHeartbeat() {
//        if (clientSocket.isConnected() && !clientSocket.isClosed()) {
//            try {
//                OutputStream outputStream = clientSocket.getOutputStream();
//                String heartbeatMessage = "5AA5"; // 定义心跳消息
//                outputStream.write(heartbeatMessage.getBytes());
//                outputStream.flush();
//                log.info("发送心跳: " + heartbeatMessage);
//
//                // 设置Socket超时
//                clientSocket.setSoTimeout(5000); // 设置超时为5秒
//                String reply = waitForHeartbeatReply(); // 等待客户端的回复
//
//                if (reply == null) {
//                    log.error("未收到心跳回复，认为连接已断开");
//                    stopHeartbeat();
////                    clientHandlers.remove(deviceHardwareAddr);
//                }
//            } catch (SocketTimeoutException e) {
//                log.error("心跳超时，未收到回复");
//                stopHeartbeat();
////                clientHandlers.remove(deviceHardwareAddr);
//            } catch (IOException e) {
//                log.error("发送心跳时出错: " + e.getMessage());
//                stopHeartbeat();
//            }
//        }
//    }
//
//    private String waitForHeartbeatReply() {
//        try {
//            BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//            return reader.readLine(); // 等待客户端的回复
//        } catch (IOException e) {
//            log.error("接收心跳回复时出错: " + e.getMessage());
//            return null;
//        }
//    }
//    public void stopHeartbeat() {
//        if (heartbeatScheduler != null && !heartbeatScheduler.isShutdown()) {
//            heartbeatScheduler.shutdown(); // 停止心跳调度
//        }
//    }
//}